<?php
declare(strict_types=1);
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/3/31 12:06
 */

namespace App\Middleware;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\HyperfAuth\AuthManager;
use Qbhy\HyperfAuth\Guard\JwtGuard;
class WebSocketAuth implements MiddlewareInterface
{
    protected ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {

        // 伪代码，通过 isAuth 方法拦截握手请求并实现权限检查
        if (! $this->isAuth($request)) {
            return $this->container->get(\Hyperf\HttpServer\Contract\ResponseInterface::class)->raw('Forbidden');
        }

        return $handler->handle($request);
    }


    protected function isAuth(ServerRequestInterface $request)
    {
        $token = $request->getQueryParams()['token'] ?? null;


        $auth = $this->container->get(AuthManager::class);

        $res = $auth->check($token);
        var_dump($res);

        $userId = $auth->id();

        var_dump($userId);
        return true;
//        $jwtGuard = $this->container->get(JwtGuard::class);
//        return $jwtGuard->check($token);
    }
}